# ActsAsCountable
module Jesse
  module Acts #:nodoc:
    
    module Countable #:nodoc:

      def self.included(base)
        base.extend ClassMethods
      end
    
      module ClassMethods
        def acts_as_countable
          has_many :counts, :as => :countable, :dependent => :destroy, :order => 'created_at DESC'
          include Jesse::Acts::Countable::InstanceMethods
          extend Jesse::Acts::Countable::SingletonMethods
        end
      end
      
      module SingletonMethods
        def find_counts_for(obj)
          countable = ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s
          
          Count.find(:first,
            :conditions => ["countable_id = ? and countable_type = ?", obj.id, countable])
        end    
      end
      
      module InstanceMethods
        def counter
          Count.find(:first,
            :conditions => ["countable_id = ? and countable_type = ?", id, self.type.name])
        end
        
        # Helper method that defaults the submitted time.
        def add_count(count)
          counter = Count.find(:first, :conditions => ["countable_id = ? and countable_type = ?", count.countable_id, self.type.name ])
          if counter.nil?
            counts << count           
          else
            counter.update_attribute(:count, counter.count + 1)
          end
        end        
      end

    end
    
  end
end